﻿var path = "http://messengerconnectsharingbadge.mslivelabs.com/icons/";
var processed = 0;
function loadScript(path, callback, target) {
    var s = document.createElement('script');
    s.onreadystatechange = function () {
        if (this.readyState == 'loaded' || this.readyState == 'complete') callback();
    }
    s.src = path;
    s.onload = callback;

    if (!target)
        target = document.getElementsByTagName('head')[0];

    target.appendChild(s);
}

if (!('jQuery' in window)) {
    loadScript('http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js', ready);
}

function ready() {
    jQuery(document).ready(function () {
        var scripts = jQuery('script');
        scripts.each(
                function () {
                    var script = jQuery(this)[0];
                    var isScript = script.src.indexOf("badge.js");
                    var isScriptDebug = script.src.indexOf("badge.debug.js");
                    if (isScript == -1 && isScriptDebug == -1) {
                        return;
                    } else {
                        var params = getQueryStringValues(script.src);

                        if (isCorrectLocale(params, 'locale')) {
                            processBadges(params);
                        }
                    }
                }
            );
    });
}

function getQueryStringValues(url) {
    var params = new Object();
    url.replace(
                new RegExp("([^?=&]+)(=([^&]*))?", "g"),
                function ($0, $1, $2, $3) {
                    params[$1] = $3;
                }
            );
    return params;
}

function isCorrectLocale(params) {
    var locale = "";
    if (params['locale'] === undefined) {
        return true;
    }

    locale = unescape(params['locale']);
    locale = locale.toLowerCase();

    var browserLocale = "";
    if (navigator.language !== undefined) {
        browserLocale = navigator.language.toLowerCase();
    } else {
        browserLocale = navigator.browserLanguage.toLowerCase();
    }

    var locales = locale.split(';', 5);
    for (var i = 0; i < locales.length; i++) {
        if (locales[i].indexOf('-') != -1) {
            if (locales[i] == browserLocale) {
                return true;
            }
        } else {
            if (locales[i] != "" && browserLocale.indexOf(locales[i]) != -1) {
                return true;
            }
        }
    }
    return false;
}

function processBadges(params) {
    if (processed == 0) {
        processed = 1;

        var iconParam = htmlEncode(unescape(params['icon']));
        var urlRegexp = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
        var isUrl = urlRegexp.test(iconParam);
        var icon = path + "32.png";

        if (isUrl) {
            icon = iconParam;
        } else {
            icon = path + iconParam + ".png";
        }

        setLinks(params);

        //jQuery('a.messenger-badge').prepend('<img src="' + icon + '" alt="Messenger Share" title="Share with your Messenger friends" style="border:none; cursor:hand"/>');
    }
}

function setLinks(params) {
    var links = jQuery('a.msn');
    links.each(function () {
        if (this.href !== "" && params['meta'] == 'graph' & jQuery(this).attr('href') !== "#") {
            jQuery.ajax({
                url: this.href,
                context: this,
                datatype: 'html',
                success: function (data) {
                    setSharingLink(data, this, params);
                }
            });
        } else {
            setSharingLink(document.getElementsByTagName('html')[0].innerHTML, this, params);
        }
    });
}

function setSharingLink(data, domLink, params) {
    var title = "";
    var description = "";
    var image = "";

    var metaRegex = /<[\s]*meta[\s]*name[\s]*=[\s]*["\']?([^>"\']*)["\']?[\s]*content[\s]*=[\s]*["\']?([^>"\']*)["\']?[\s]*[\/]?[\s]*>/ig;
    while (arrMatch = metaRegex.exec(data)) {
        if (jQuery.trim(arrMatch[1].toLowerCase()) == "title") {
            title = jQuery.trim(arrMatch[2]);
        } else if (jQuery.trim(arrMatch[1].toLowerCase()) == "description") {
            description = jQuery.trim(arrMatch[2]);
        }
    }

    var imageRegex = /<[\s]*link[\s]*rel[\s]*=[\s]*["\']?([^>"\']*)["\']?[\s]*href[\s]*=[\s]*["\']?([^>"\']*)["\']?[\s]*[\/]?[\s]*>/ig;
    while (arrMatch = imageRegex.exec(data)) {
        if (jQuery.trim(arrMatch[1].toLowerCase()) == "image_src") {
            image = jQuery.trim(arrMatch[2]);
        }
    }

    if (title == "" && (params['meta'] != 'oexchange')) {
        var graphRegex = /<[\s]*meta[\s]*property[\s]*=[\s]*["\']?([^>"\']*)["\']?[\s]*content[\s]*=[\s]*["\']?([^>"\']*)["\']?[\s]*[\/]?[\s]*>/ig;
        while (arrMatch = graphRegex.exec(data)) {
            if (jQuery.trim(arrMatch[1].toLowerCase()) == "og:title") {
                title = jQuery.trim(arrMatch[2]);
            } else if (jQuery.trim(arrMatch[1].toLowerCase()) == "og:description") {
                description = jQuery.trim(arrMatch[2]);
            } else if (jQuery.trim(arrMatch[1].toLowerCase()) == "og:image") {
                image = jQuery.trim(arrMatch[2]);
            }
        }
        if (title == "") {
            var titleRegex = /<[\s]*title[\s]*>[\s]*["\']?([^>"\']*)<[\s]*[\/]?title[\s]*>/ig;
            while (arrMatch = titleRegex.exec(data)) {
                title = jQuery.trim(arrMatch[1]);
                description = title;
            }
        }
    }

    var url = jQuery(domLink).attr('href');
    var isCurrentSite = url.indexOf("http://");
    var isCurrentUrl = false;
    if (isCurrentSite == -1 && url != '' && url != '#') {
        url = domLink.href;
    }else if (url == '' || url == '#') {
        url = document.location.toString();
        isCurrentUrl = true;
    }

    url = addParam(url, params, 'utm_source');
    url = addParam(url, params, 'utm_medium');
    url = addParam(url, params, 'utm_campaign');
    url = addParam(url, params, 'utm_content');
    var link = "";

    if (!isCurrentUrl && params['meta'] == 'oexchange') {
        link = createBadgeUrl(url, "", "", "");
    } else {
        link = createBadgeUrl(url, title, description, image);
    }
    jQuery(domLink).click(function () {
        window.open(link, '', 'width=1000,height=600,toolbar=no');
        return false;
    });
}

function addParam(url, params, param) {
    if (params[param] !== undefined) {
        if (url.indexOf('?', 0) == -1) {
            url += '?';
        } else {
            url += '&';
        }
        url += param + '=' + params[param];
    }

    return url;
}
function htmlEncode(s) {
    return s.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/&/g, "&amp;").replace(/"/g, "&quot;");
}
function createBadgeUrl(url, title, description, image) {
    var link = "http://profile.live.com/badge/?url={0}";
    link = link.replace("{0}", escape(url));
    if (title !== undefined && title != "") {
        link += '&title=' + escape(title);
    }
    if (description !== undefined && description != "") {
        link += '&description=' + escape(description);
    }
    if (image !== undefined && image != "") {
        link += '&screenshot=' + escape(image)
    }
    return link;
}
